import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Typography,
  Space,
  Badge,
  Avatar,
  List,
  Tag,
  Calendar,
  Progress,
  Statistic,
  Button,
  Empty,
} from "antd";
import {
  UserOutlined,
  BookOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BellOutlined,
  FileTextOutlined,
  FormOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  StudentInfo,
  CourseInfo,
  HomeworkInfo,
  ExamInfo,
  Notification,
  LearningProgress,
} from "../types";

const { Title, Text } = Typography;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

interface DashboardItem {
  id: string;
  type: "exam" | "homework";
  courseId: string;
  courseName: string;
  data: ExamInfo | HomeworkInfo;
}

const StudentDashboard: React.FC = () => {
  const [studentInfo, setStudentInfo] = useState<StudentInfo>();
  const [courses, setCourses] = useState<CourseInfo[]>([]);
  const [homework, setHomework] = useState<HomeworkInfo[]>([]);
  const [exams, setExams] = useState<ExamInfo[]>([]);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [progress, setProgress] = useState<LearningProgress>();

  useEffect(() => {
    // TODO: 替换为实际的 API 调用
    // 模拟加载数据
    setStudentInfo({
      id: "1",
      name: "张三",
      studentId: "2021001",
      className: "计算机科学与技术1班",
      major: "计算机科学与技术",
      grade: "2021级",
      email: "zhangsan@example.com",
    });

    setCourses([
      {
        id: "1",
        name: "操作系统",
        teacherName: "李老师",
        semester: "2023-2024-2",
        schedule: "周一 1-2节",
        classroom: "A301",
        credit: 4,
      },
      // ... 其他课程
    ]);

    setHomework([
      {
        id: "1",
        title: "操作系统实验一",
        courseId: "1",
        deadline: "2024-03-20 23:59:59",
        description: "完成进程调度模拟实验",
        status: "pending",
      },
      // ... 其他作业
    ]);

    setExams([
      {
        id: "1",
        name: "操作系统期中考试",
        courseId: "1",
        startTime: "2024-04-15 14:00:00",
        endTime: "2024-04-15 16:00:00",
        duration: 120,
        totalScore: 100,
        status: "upcoming",
      },
      // ... 其他考试
    ]);

    setNotifications([
      {
        id: "1",
        title: "新作业通知",
        content: "操作系统课程发布了新的作业",
        type: "homework",
        time: "2024-03-15 10:00:00",
        read: false,
        link: "/homework/1",
      },
      // ... 其他通知
    ]);

    setProgress({
      courseId: "1",
      attendance: {
        total: 32,
        present: 30,
        late: 1,
        absent: 1,
      },
      homework: {
        total: 10,
        submitted: 8,
        graded: 7,
        averageScore: 85,
      },
      exams: {
        total: 2,
        completed: 1,
        averageScore: 88,
        ranking: 15,
      },
      knowledgePoints: {
        进程管理: {
          mastery: 85,
          recentTrend: [70, 75, 85],
          needsImprovement: false,
        },
        内存管理: {
          mastery: 75,
          recentTrend: [65, 70, 75],
          needsImprovement: true,
        },
      },
    });
  }, []);

  const mockItems: DashboardItem[] = [
    {
      id: "1",
      type: "exam",
      courseId: "c1",
      courseName: "高级Web开发",
      data: {
        id: "e1",
        name: "期中考试",
        courseId: "c1",
        startTime: "2024-04-15 14:00",
        endTime: "2024-04-15 16:00",
        duration: 120,
        totalScore: 100,
        status: "upcoming",
      },
    },
    {
      id: "2",
      type: "homework",
      courseId: "c1",
      courseName: "高级Web开发",
      data: {
        id: "h1",
        title: "第一次作业",
        courseId: "c1",
        deadline: "2024-03-20",
        description: "完成课程项目的需求分析文档",
        status: "pending",
      },
    },
  ];

  const getItemTitle = (item: DashboardItem) => {
    if (item.type === "exam") {
      return (item.data as ExamInfo).name;
    }
    return (item.data as HomeworkInfo).title;
  };

  const getItemIcon = (type: DashboardItem["type"]) => {
    switch (type) {
      case "exam":
        return <BookOutlined />;
      case "homework":
        return <FormOutlined />;
      default:
        return null;
    }
  };

  return (
    <div style={{ padding: "24px" }}>
      {/* 个人信息卡片 */}
      <StyledCard>
        <Row gutter={24} align="middle">
          <Col>
            <Avatar size={64} icon={<UserOutlined />} />
          </Col>
          <Col>
            <Space direction="vertical">
              <Title level={4}>{studentInfo?.name}</Title>
              <Space>
                <Text type="secondary">学号：{studentInfo?.studentId}</Text>
                <Text type="secondary">班级：{studentInfo?.className}</Text>
                <Text type="secondary">专业：{studentInfo?.major}</Text>
              </Space>
            </Space>
          </Col>
        </Row>
      </StyledCard>

      <Row gutter={24}>
        <Col span={16}>
          {/* 待办事项 */}
          <StyledCard
            title={
              <Space>
                <ClockCircleOutlined />
                <span>待办事项</span>
              </Space>
            }
          >
            <List
              itemLayout="horizontal"
              dataSource={mockItems}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={getItemIcon(item.type)}
                    title={getItemTitle(item)}
                    description={
                      <Space>
                        <Tag color={item.type === "homework" ? "blue" : "red"}>
                          {item.type === "homework" ? "作业" : "考试"}
                        </Tag>
                        <span>
                          <ClockCircleOutlined />{" "}
                          {item.type === "homework"
                            ? `截止日期：${(item.data as HomeworkInfo).deadline}`
                            : `考试时间：${(item.data as ExamInfo).startTime}`}
                        </span>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </StyledCard>

          {/* 学习进度 */}
          <StyledCard
            title={
              <Space>
                <CheckCircleOutlined />
                <span>学习进度</span>
              </Space>
            }
          >
            <Row gutter={[24, 24]}>
              <Col span={8}>
                <Statistic
                  title="出勤率"
                  value={
                    ((progress?.attendance.present || 0) /
                      (progress?.attendance.total || 1)) *
                    100
                  }
                  suffix="%"
                  precision={1}
                />
                <Progress
                  percent={
                    ((progress?.attendance.present || 0) /
                      (progress?.attendance.total || 1)) *
                    100
                  }
                  status="active"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="作业完成率"
                  value={
                    ((progress?.homework.submitted || 0) /
                      (progress?.homework.total || 1)) *
                    100
                  }
                  suffix="%"
                  precision={1}
                />
                <Progress
                  percent={
                    ((progress?.homework.submitted || 0) /
                      (progress?.homework.total || 1)) *
                    100
                  }
                  status="active"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="平均成绩"
                  value={progress?.homework.averageScore || 0}
                  suffix="/100"
                />
                <Progress
                  percent={progress?.homework.averageScore || 0}
                  status="active"
                />
              </Col>
            </Row>
          </StyledCard>
        </Col>

        <Col span={8}>
          {/* 课程表 */}
          <StyledCard
            title={
              <Space>
                <BookOutlined />
                <span>课程表</span>
              </Space>
            }
          >
            <Calendar fullscreen={false} />
          </StyledCard>

          {/* 通知公告 */}
          <StyledCard
            title={
              <Space>
                <BellOutlined />
                <span>通知公告</span>
              </Space>
            }
          >
            <List
              dataSource={notifications}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Badge dot={!item.read}>
                        <Avatar icon={<BellOutlined />} />
                      </Badge>
                    }
                    title={item.title}
                    description={
                      <Space>
                        <Tag
                          color={item.type === "homework" ? "blue" : "green"}
                        >
                          {item.type}
                        </Tag>
                        <Text type="secondary">
                          {item.time.substring(0, 16)}
                        </Text>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </StyledCard>
        </Col>
      </Row>
    </div>
  );
};

export default StudentDashboard;
